package me.yobol.greentable.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import me.yobol.greentable.bean.DishesBean;
import me.yobol.greentable.bean.DishesCommentBean;
import me.yobol.greentable.service.DishesCommentService;
import me.yobol.greentable.service.DishesService;
import me.yobol.greentable.service.UserService;

/**
 * @author Yobol
 *
 */
public class GetDishesServlet extends HttpServlet {

	private static final long serialVersionUID = -8865425543851982834L;

	public GetDishesServlet() {
		super();
	}

	public void init() throws ServletException {
		// Put your code here
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		int dishesId = (request.getParameter("dishesId") == null) ? -1
				: Integer.parseInt(request.getParameter("dishesId"));

		DishesBean dishes = DishesService.getDishesByDishesId(dishesId);
		String forwardUrl = null;
		
		if(dishes != null){
			int scansCtr = dishes.getDishesScansCtr();
			if(DishesService.updateDishesScansCtr(dishesId, ++scansCtr)){
				dishes = DishesService.getDishesByDishesId(dishesId);
				
				String dishesOwnerName = UserService.getUNameByUID(dishes.getDishesOwner());

				request.getSession().setAttribute("dishes", dishes);
				request.getSession().setAttribute("dishesOwnerName", dishesOwnerName);

				List<DishesCommentBean> comments = DishesCommentService.getDishesCommentByDishesId(dishesId);
				request.getSession().setAttribute("dishesComments", comments);
				forwardUrl = "/pages/dishes.jsp";
			}
		}else{
			//give a feedback that no such dishes
		}
		RequestDispatcher rd = request.getRequestDispatcher(forwardUrl);
		rd.forward(request, response);
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

}
